package com.cocoiko;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.cocoiko.customview.FriendListAdapter;
import com.cocoiko.info.FriendInfo;
import com.cocoiko.tools.facebook.FacebookUtils;
import com.cocoiko.tools.twitter.Constants;
import com.cocoiko.tools.twitter.TwitterUtils;
import com.cocoiko.utils.CocoikoConstains;
import com.cocoiko.utils.CocoikoUtils;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;

public class FriendList extends Activity implements OnClickListener,
		OnItemClickListener, OnScrollListener {

	final static String FACEBOOK = "Facebook";
	final static String TWITTER = "Twitter";
	final static String CONTACT = "Contact";

	Button back;
	TextView title_textview;
	ListView listfriend;

	String title;

	ArrayList<FriendInfo> friends;
	FriendListAdapter adapter = null;

	ProgressDialog progress;

	Thread loadFriendThread;

	LoadingFacebookUserProfilePicture load;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_list_act_layout);

		// get view
		back = (Button) findViewById(R.id.back);
		title_textview = (TextView) findViewById(R.id.title);
		listfriend = (ListView) findViewById(R.id.listfriend);

		// set listener
		back.setOnClickListener(this);
		listfriend.setOnItemClickListener(this);

		listfriend.setOnScrollListener(this);
		// get account info
		Bundle bundle = getIntent().getExtras();
		title = bundle.getString("title");
		if (title.equals(FACEBOOK)) {
			title_textview.setText("Facebookの友達");
		} else if (title.equals(TWITTER)) {
			title_textview.setText("Twitterの友達");
		} else {
			title_textview.setText("連絡から探す");
		}
		// start search friend
		progress = ProgressDialog.show(this, "", "wait for a few minute ...");
		loadFriendThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (title.equals(FACEBOOK)) {
					searchFacebookFriend();
				} else if (title.equals(TWITTER)) {
					searchTwitterFriend();
				} else {
					searchFriendFromContact();
				}
				handle.sendEmptyMessage(RESULT_OK);
			}

			private void stop() {
				// TODO Auto-generated method stub

			}
		});
		loadFriendThread.start();

	}

	/**
	 * dismiss progress and show result in listview
	 */
	private Handler handle = new Handler() {
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);

			addToFriendListView(friends);
			progress.dismiss();

			load = new LoadingFacebookUserProfilePicture();
			load.execute();

		};
	};

	/**
	 * 
	 */
	Handler loadPictureHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			addToFriendListView(friends);
		};
	};

	/*
	 * friend from contact
	 */
	public void searchFriendFromContact() {
		friends = new ArrayList<FriendInfo>();

		// search friend from contack at here
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.icon);
		FriendInfo friend = new FriendInfo(bitmap, "le van nghia",
				"nghialv.bk@gmail.com");
		friends.add(friend);

	}

	/*
	 * facebook friend
	 */
	public void searchFacebookFriend() {

		friends = new ArrayList<FriendInfo>();
		SharedPreferences prefs = getSharedPreferences(
				CocoikoConstains.FACEBOOK_SESSION, MODE_PRIVATE);
		FacebookUtils.getFriendList(prefs, new FriendsRequestListener());

	}

	/*
	 * twitter friend
	 */
	public void searchTwitterFriend() {

		// search twitter friend at here
		SharedPreferences prefs = getSharedPreferences(
				CocoikoConstains.SHARE_PREFER_NAME, MODE_PRIVATE);
		friends = TwitterUtils.getFriendsList(prefs);

	}

	/*
	 * 
	 */
	public void addToFriendListView(ArrayList<FriendInfo> datas) {

		adapter = new FriendListAdapter(this, R.layout.friend_listview, datas);
		listfriend.setAdapter(adapter);

	}

	/**
	 * 
	 */
	public void stopAllThread() {
		if (load != null) {
			load.cancel(true);
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if (view == back) {
			stopAllThread();
			finish();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		// click list item to show friend info
		FriendInfo friend = friends.get(position);

		// start show info activity at here
	}

	/**
	 * facebook friends request listener
	 * 
	 * @author kaze
	 * 
	 */
	public class FriendsRequestListener implements RequestListener {

		@Override
		public void onComplete(String response, Object state) {
			// TODO Auto-generated method stub
			try {
				// process the response here: executed in background thread
				Log.d("Facebook-Friends Request", "response.length(): "
						+ response.length());
				Log.d("Facebook-Friends Request", "Response: " + response);

				final JSONObject json = new JSONObject(response);
				JSONArray d = json.getJSONArray("data");
				int l = (d != null ? d.length() : 0);
				Log.d("Facebook-Friends Request", "d.length(): " + l);

				for (int i = 0; i < l; i++) {
					JSONObject o = d.getJSONObject(i);
					String n = o.getString("name");
					String id = o.getString("id");
					FriendInfo f = new FriendInfo();
					f.setId(Long.valueOf(id));
					f.setName(n);

					// picture
					Bitmap bitmap = null;

					try {
						URL url = new URL("http://graph.facebook.com/" + id
								+ "/picture");

						// add profile picture url
						f.setUrl(url);

						if (i < 10) {
							bitmap = CocoikoUtils.getBitmapFromUrl(url);
							Log.i("bitmap:", bitmap.toString());
							f.setAvatar(bitmap);
						}
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					friends.add(f);
				}

				handle.sendEmptyMessage(0);

			} catch (JSONException e) {
				Log.w("Facebook", "JSON Error in response");
			}

		}

		@Override
		public void onFacebookError(FacebookError e, Object state) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFileNotFoundException(FileNotFoundException e,
				Object state) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onIOException(IOException e, Object state) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onMalformedURLException(MalformedURLException e,
				Object state) {
			// TODO Auto-generated method stub

		}

	}

	public class LoadingFacebookUserProfilePicture extends
			AsyncTask<Integer, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			for (int i = 0; i < friends.size(); i++) {

				FriendInfo f = friends.get(i);
				if (f.getAvatar() == null) {
					Bitmap bitmap = CocoikoUtils.getBitmapFromUrl(friends
							.get(i).getUrl());
					friends.get(i).setAvatar(bitmap);
					Log.i("Downloaded", String.valueOf(i));
				}
				if (isCancelled())
					break;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean state) {
			// TODO Auto-generated method stub
			super.onPostExecute(state);
			if (state)
				addToFriendListView(friends);
		}

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if (adapter != null) {
			// adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		stopAllThread();
	}

}
